//
//  YBLoginViewController.m
//  ShangHaiHuDongApp
//
//  Created by apple on 18/6/2.
//  Copyright © 2018年 刘应平. All rights reserved.
//

#import "YBLoginViewController.h"
#import "YBRegisterViewController.h"
#import "CManager.h"
#import "ZJTabBarController.h"
#import "HomeMenuViewController.h"
#import "ElectiveViewController.h"
#import "YBElectiveViewController.h"

#import "SubjectViewController.h"
#import "MyViewController.h"
#import "YBRegisterViewController.h"
#import "YBFindPasswordViewController.h"

@interface YBLoginViewController ()<UITextFieldDelegate , UITabBarControllerDelegate>
@property (nonatomic , strong) UIImageView * headImageView;

@property (nonatomic , strong) UITextField * usernameTextField;

@property (nonatomic , strong) UITextField * passwordTextField;

@property (nonatomic , strong) UIButton * loginButton;

@property (nonatomic , strong) UIButton * registerButton;
@end

@implementation YBLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initUserInterface];
    self.titlelabel.text = @"中物院云课堂";
    if (self.navigationController.viewControllers.count == 1) {
        self.leftButton.hidden = YES;
    }
}

-(void)initUserInterface{
    [self.view addSubview:self.headImageView];
    [self.view addSubview:self.usernameTextField];
    [self.view addSubview:self.passwordTextField];
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.registerButton];
    
    UIButton * findPasswordButton = [ToolClass createButtonWithFrame:CGRectMake(0, 0, 1, 1) text:@"找回密码" textColor:[UIColor themeColor] imageName:@"" font:15];
    [findPasswordButton addTarget:self action:@selector(option_findPasswordButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:findPasswordButton];
    
    self.headImageView.sd_layout.topSpaceToView(self.navigView , 0)
    .leftSpaceToView(self.view , 0)
    .rightSpaceToView(self.view , 0)
    .heightIs(ItemHeight * 534);
    
    self.usernameTextField.sd_layout.topSpaceToView(self.headImageView , ItemHeight * 42)
    .leftSpaceToView(self.view , ItemWidth * 75)
    .rightSpaceToView(self.view , ItemWidth * 75)
    .heightIs(ItemHeight * 88);
    
    self.passwordTextField.sd_layout.topSpaceToView(self.usernameTextField , ItemHeight * 24)
    .leftSpaceToView(self.view , ItemWidth * 75)
    .rightSpaceToView(self.view , ItemWidth * 75)
    .heightIs(ItemHeight * 88);
    
    findPasswordButton.sd_layout.topSpaceToView(self.passwordTextField , ItemHeight * 5)
    .leftSpaceToView(self.view , ItemWidth * 75)
    .widthIs(ItemWidth * 160)
    .heightIs(ItemHeight * 88);
    
    self.registerButton.sd_layout.topSpaceToView(self.passwordTextField , ItemHeight * 5)
    .rightSpaceToView(self.view , ItemWidth * 75)
    .widthIs(ItemWidth * 160)
    .heightIs(ItemHeight * 88);
    
//    self.registerButton.sd_layout.bottomSpaceToView(self.view , ItemHeight * 72)
//    .leftSpaceToView(self.view , ItemWidth * 75)
//    .rightSpaceToView(self.view , ItemWidth * 75)
//    .heightIs(ItemHeight * 88);
    
    self.loginButton.sd_layout.bottomSpaceToView(self.view , ItemHeight * 72)
        .leftSpaceToView(self.view , ItemWidth * 75)
        .rightSpaceToView(self.view , ItemWidth * 75)
        .heightIs(ItemHeight * 88);
    
}

-(void)option_findPasswordButton:(UIButton *)sender{
    YBFindPasswordViewController * findVC = [[YBFindPasswordViewController alloc]init];
    if ([CManager zj_validateMobile:self.usernameTextField.text]) {
        findVC.phoneString = self.usernameTextField.text;
    }
    else{
        findVC.phoneString = @"";
    }
    [self.navigationController pushViewController:findVC animated:YES];
}


-(void)option_regiserWithButton:(UIButton *)sender{
    
//    if (self.usernameTextField.text.length == 0) {
//        [YJProgressHUD showMessage:@"账号不可为空" inView:self.view afterDelayTime:2.f];
//        return;
//    }
//    if (self.passwordTextField.text.length == 0) {
//        [YJProgressHUD showMessage:@"密码不可为空" inView:self.view afterDelayTime:2.f];
//        return;
//    }
//    if (self.passwordTextField.text.length < 6) {
//        [YJProgressHUD showMessage:@"密码长度必须大于6位" inView:self.view afterDelayTime:2.f];
//        return;
//    }
    YBRegisterViewController * registerVC = [[YBRegisterViewController alloc]init];
//    if ([CManager zj_validateMobile:self.usernameTextField.text]) {
//        registerVC.phoneString = self.usernameTextField.text;
//    }
//    else{
//        registerVC.phoneString = @"";
//    }
//    registerVC.username = self.usernameTextField.text;
//    registerVC.password = self.passwordTextField.text;
    [self.navigationController pushViewController:registerVC animated:YES];
}



-(void)option_loginWithButton:(UIButton *)sender{
    if (self.usernameTextField.text.length == 0) {
        [YJProgressHUD showMessage:@"账号不可为空" inView:self.view afterDelayTime:2.f];
        return;
    }
    if (self.passwordTextField.text.length == 0) {
        [YJProgressHUD showMessage:@"密码不可为空" inView:self.view afterDelayTime:2.f];
        return;
    }
    if (self.passwordTextField.text.length < 6) {
        [YJProgressHUD showMessage:@"密码长度必须大于6位" inView:self.view afterDelayTime:2.f];
        return;
    }
    [YJProgressHUD showMessage:@"正在登录中" duration:30 view:self.view];
    
    
//    YBRegisterViewController * registerVC = [[YBRegisterViewController alloc]init];
//    if ([CManager zj_validateMobile:self.usernameTextField.text]) {
//        registerVC.phoneString = self.usernameTextField.text;
//    }
//    else{
//        registerVC.phoneString = @"";
//    }
//    registerVC.username = self.usernameTextField.text;
//    registerVC.password = self.passwordTextField.text;
//    [self.navigationController pushViewController:registerVC animated:YES];
    
    
    [YBRequestManager request_loginWithUsername:self.usernameTextField.text password:self.passwordTextField.text successBlock:^(id object) {
        [YJProgressHUD hide];
        if ([object[@"code"] integerValue] == 1) {
            if ([object[@"data"][@"result"] integerValue] == 1) {
                [self rememberUserInfoWithDic:object[@"data"]];
                [YJProgressHUD showMessage:@"登录成功" inView:self.view compeleteBlock:^{
                    ZJTabBarController * rootViewController = [ZJTabBarController new];
                    rootViewController.delegate = self;
                    UINavigationController * mainNav = [[UINavigationController alloc]initWithRootViewController:rootViewController];
                    mainNav.navigationBar.hidden = YES;
                    [UIApplication sharedApplication].keyWindow.rootViewController = mainNav;
                    [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
                }];
                
            }
            else{
                if ([object[@"data"][@"index"] integerValue] == -1) {
                    YBRegisterViewController * registerVC = [[YBRegisterViewController alloc]init];
                    if ([CManager zj_validateMobile:self.usernameTextField.text]) {
                        registerVC.phoneString = self.usernameTextField.text;
                    }
                    else{
                        registerVC.phoneString = @"";
                    }
                    registerVC.username = self.usernameTextField.text;
                    registerVC.password = self.passwordTextField.text;
                    [self.navigationController pushViewController:registerVC animated:YES];
                }
                else{
                    [YJProgressHUD showMsgWithoutView:[NSString stringWithFormat:@"%@" , object[@"data"][@"message"]]];
                }
            }
        }
        else{
            [YJProgressHUD showMsgWithoutView:@"登录失败"];
        }
        
    } failBlock:^(id object) {
        [YJProgressHUD showMsgWithoutView:@"登录失败"];
    }];
}

-(void)rememberUserInfoWithDic:(NSDictionary *)dic{
    [[NSUserDefaults standardUserDefaults] setObject:dic[@"token"] forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] setObject:dic[@"loginUser"] forKey:@"loginUser"];
    [[NSUserDefaults standardUserDefaults] setObject:dic[@"loginUser"][@"sessionId"] forKey:@"sessionId"];
    [[NSUserDefaults standardUserDefaults] setObject:self.usernameTextField.text forKey:@"username"];
    [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"password"];
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    if ([viewController isKindOfClass:[HomeMenuViewController class]]) {
        return YES;
    }else if ([viewController isKindOfClass:[YBElectiveViewController class]]) {
        return [self isLoging];
    }else if ([viewController isKindOfClass:[SubjectViewController class]]) {
        return  [self isLoging];
    }else if ([viewController isKindOfClass:[MyViewController class]]) {
        return [self isLoging];
    }
    return YES;
}

- (BOOL)isLoging{
    if (YBUSERINFOMODEL.studentId.length > 0) {
        return YES;
    }else{//未登录
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"请先登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            YBLoginViewController *vc = [YBLoginViewController new];
            [[ToolClass getMainNavigationController] pushViewController:vc animated:YES];
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [[ToolClass getMainNavigationController] presentViewController:alertController animated:YES completion:nil];
        
        return NO;
    }
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


-(UIImageView *)headImageView
{
    if (!_headImageView) {
        _headImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        _headImageView.image = [UIImage imageNamed:@"iconimg"];
    }
    return _headImageView;
}


-(UITextField *)usernameTextField
{
    if (!_usernameTextField) {
        _usernameTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        _usernameTextField.placeholder = @"请输入手机号/账户号";
        _usernameTextField.leftViewMode = UITextFieldViewModeAlways;
        _usernameTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        UIView * leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ItemWidth * 70, ItemHeight * 88)];
        UIImageView * leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(ItemWidth * 16, ItemWidth * 24, ItemWidth * 38, ItemWidth * 38)];
        leftImageView.image = [UIImage imageNamed:@"username"];
        [leftView addSubview:leftImageView];
        _usernameTextField.leftView = leftView;
        _usernameTextField.clipsToBounds = YES;
        _usernameTextField.sd_cornerRadius = @(4 * [UIScreen zj_screenHScale]);
        _usernameTextField.layer.borderColor = [UIColor zj_colorWithHexString:@"ebebeb"].CGColor;
        _usernameTextField.layer.borderWidth = 1;
        _usernameTextField.delegate = self;
        _usernameTextField.returnKeyType = UIReturnKeyDone;
        _usernameTextField.font = LYPFONT(14);
    }
    return _usernameTextField;
}


-(UITextField *)passwordTextField
{
    if (!_passwordTextField) {
        _passwordTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        _passwordTextField.placeholder = @"请输入密码";
        _passwordTextField.leftViewMode = UITextFieldViewModeAlways;
        UIView * leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ItemWidth * 70, ItemHeight * 88)];
        UIImageView * leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(ItemWidth * 16, ItemWidth * 24, ItemWidth * 38, ItemWidth * 38)];
        leftImageView.image = [UIImage imageNamed:@"password"];
        [leftView addSubview:leftImageView];
        _passwordTextField.leftView = leftView;
        _passwordTextField.clipsToBounds = YES;
        _passwordTextField.sd_cornerRadius = @(4 * [UIScreen zj_screenHScale]);
        _passwordTextField.layer.borderColor = [UIColor zj_colorWithHexString:@"ebebeb"].CGColor;
        _passwordTextField.layer.borderWidth = 1;
        _passwordTextField.font = LYPFONT(14);
        _passwordTextField.delegate = self;
        _passwordTextField.returnKeyType = UIReturnKeyDone;
        _passwordTextField.secureTextEntry = YES;
        _passwordTextField.clearsOnBeginEditing = YES;
    }
    return _passwordTextField;
}


-(UIButton *)loginButton
{
    if (!_loginButton) {
        _loginButton = [ToolClass createButtonWithFrame:CGRectMake(0, 0, 1, 1) text:@"登录" textColor:[UIColor whiteColor] imageName:@"" font:14];
        _loginButton.clipsToBounds = YES;
        _loginButton.sd_cornerRadius = @(4 * [UIScreen zj_screenHScale]);
        _loginButton.backgroundColor = [UIColor themeColor];
        [_loginButton addTarget:self action:@selector(option_loginWithButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}


-(UIButton *)registerButton
{
    if (!_registerButton) {
        _registerButton = [ToolClass createButtonWithFrame:CGRectMake(0, 0, 1, 1) text:@"激活帐号" textColor:[UIColor themeColor] imageName:@"" font:15];
//        _registerButton.clipsToBounds = YES;
//        _registerButton.sd_cornerRadius = @(4 * [UIScreen zj_screenHScale]);
//        _registerButton.backgroundColor = [UIColor themeColor];
        _registerButton.titleLabel.textAlignment = NSTextAlignmentRight;
        [_registerButton addTarget:self action:@selector(option_regiserWithButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registerButton;
}


@end
